package cn.techaction.service.Impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;

import cn.techaction.common.SverResponse;
import cn.techaction.dao.ActionAddressDao;
import cn.techaction.dao.ActionCartDao;
import cn.techaction.dao.ActionOrderDao;
import cn.techaction.dao.ActionOrderItemDao;
import cn.techaction.dao.ActionProductDao;
import cn.techaction.pojo.ActionAddress;
import cn.techaction.pojo.ActionCart;
import cn.techaction.pojo.ActionOrder;
import cn.techaction.pojo.ActionProduct;
import cn.techaction.pojo.ActionorderItem;
import cn.techaction.service.ActionOrderService;
import cn.techaction.utils.CalcUtil;
import cn.techaction.utils.ConstUtil;
import cn.techaction.utils.DateUtils;
import cn.techaction.utils.PageBean;
import cn.techaction.vo.ActionAddressVo;
import cn.techaction.vo.ActionOrderVo;
import cn.techaction.vo.ActionorderItemVo;
@Service
public class ActionOrderServiceImpl implements ActionOrderService {
	@Autowired
	private ActionOrderDao aOrderDao;
	@Autowired
	private ActionAddressDao aaddressDao;
	@Autowired
	private ActionOrderItemDao aOrderItemDao;
	@Autowired
	private ActionCartDao aCartDao;
	@Autowired
	private ActionProductDao aProductDao;

	@Override
	public SverResponse<PageBean<ActionOrderVo>> findOrders(Integer uid, Integer status, int pageNum, int pageSize) {
		// TODO Auto-generated method stub
		//判断userid是否为空
		if (uid==null) {
			return SverResponse.createByErrorMessage("参数错误！");
		}
		//查找符合条件的总记录数
		int totalRecord = aOrderDao.getTotalRecord(uid,status);
		//创建分页封装对象
		PageBean<ActionOrderVo> pageBean = new PageBean<ActionOrderVo>(pageNum, pageSize, totalRecord);
		//获得数据
		List<ActionOrder> orders=aOrderDao.findOrders(uid,status,pageBean.getStartIndex(),pageSize);
		//封装vo
		List<ActionOrderVo> voList=Lists.newArrayList();
		for (ActionOrder order:orders) {
			voList.add(createOrderVO1(order,false));
		}
		pageBean.setData(voList);
		return SverResponse.createRespBySuccess(pageBean);
	}
	
	@Override
	public SverResponse<String> cancelOrder(Integer uid, Long orderNo) {
		// TODO Auto-generated method stub
		//查询订单
		ActionOrder order = aOrderDao.findOrderByUserAndOrderNo(uid,orderNo);
		//判断订单是否存在
		if (order==null) {
			return SverResponse.createByErrorMessage("该用户订单不存在或已删除");
		}
		//判断订单是否已经付款
		if (order.getStatus()==ConstUtil.OrderStatus.ORDER_PAID) {
			return SverResponse.createByErrorMessage("该订单已经付款，无法取消");
		}
		//判断状态修改订单信息
		ActionOrder updateOrder=new ActionOrder();
		updateOrder.setId(order.getId());
		updateOrder.setUpdateTime(new Date());
		if (order.getStatus()==1) {
			updateOrder.setStatus(ConstUtil.OrderStatus.ORDER_CANCELED);
			int row=aOrderDao.updateOrder(updateOrder);
			if (row >0) {
				return SverResponse.createRespBySuccessMessage("订单取消成功");
			}
			
		}
		if (order.getStatus()==3) {
			updateOrder.setStatus(ConstUtil.OrderStatus.ORDER_SUCCESS);
			int row=aOrderDao.updateOrder(updateOrder);
			if (row >0) {
				return SverResponse.createRespBySuccessMessage("订单已经确认收货");
			}
			
		}
		return SverResponse.createByErrorMessage("操作执行失败");
	}

	@Override
	public SverResponse<ActionOrderVo> findOrderDetail(Integer uid, Long orderNo) {
		// TODO Auto-generated method stub
		//判断参数是否正确
		if (uid==null||orderNo==null) {
			return SverResponse.createByErrorMessage("参数错误");
		}
		//查找订单封装
		ActionOrder order =aOrderDao.findOrderByUserAndOrderNo(uid, orderNo);
		if (order==null) {
			return SverResponse.createByErrorMessage("该用户订单不存在或已经删除");
		}
		ActionOrderVo orderVo=createOrderVO1(order, true);
		return SverResponse.createRespBySuccess(orderVo);
	}

	@Override
	public SverResponse<ActionOrderVo> generateOrder(Integer uid, Integer addrId) {
		// TODO Auto-generated method stub
		//提取购物车信息
		List<ActionCart> carts = aCartDao.findCartByUser(uid);
		for(ActionCart cart:carts) {
			aCartDao.deleteCarts(cart.getUserId(), cart.getProductId());
		}
		//计算购物车中每件商品总价格并生成订单项
		SverResponse resp = this.cart2OrderItem(uid,carts);
		if (!resp.isSuccess()) {
			return resp;
		}
		//取出订单项中的价格计算订单总价格
		List<ActionorderItem> orderItems =(List<ActionorderItem>)resp.getData();
		BigDecimal totalPrice=this.calcOrderTotalPrice(orderItems);
		//生成订单插入数据
		ActionOrder order =saveOrder(uid,addrId,totalPrice);
		if (order ==null) {
			return SverResponse.createByErrorMessage("订单生产错误");
		}
		if (CollectionUtils.isEmpty(orderItems)) {
			return SverResponse.createByErrorMessage("订单项为空");
		}
		//批量插入订单项
		for(ActionorderItem orderItem:orderItems) {
			//为订单项设置主键
			orderItem.setOrderNo(order.getOrderNo());
		}
		aOrderItemDao.batchInsert(orderItems);
		//减少商品表中库存
		for(ActionorderItem orderItem:orderItems) {
			ActionProduct product =aProductDao.findProductById(orderItem.getGoodsId());
			//减少库存
			product.setStock(product.getStock() - orderItem.getQuantity());
			product.setUpdated(new Date());
			//更新库存
			aProductDao.updateProduct(product);
		}
		//清空购物车
		aProductDao.deleteCartProduct(uid);
		//封装返回对象
		ActionOrderVo orderVo=createOrderVO(order, orderItems);
		
		return SverResponse.createRespBySuccess(orderVo);
	}
	
	//封装订单vo
		private ActionOrderVo createOrderVO(ActionOrder order, List<ActionorderItem> orderItems) {
			// TODO Auto-generated method stub
			ActionOrderVo OrderVo = new ActionOrderVo();
			setNormalProperty(order,OrderVo);
			setAddressProperty(order,OrderVo,true);
			setOrderItemProperty(orderItems,OrderVo);
			return OrderVo;
		}
	
	//封装vo
	private ActionOrderVo createOrderVO1(ActionOrder order, boolean hasAdress) {
		// TODO Auto-generated method stub
		ActionOrderVo OrderVo = new ActionOrderVo();
		setNormalProperty(order,OrderVo);
		setAddressProperty(order,OrderVo,hasAdress);
		//设置订单项
		List<ActionorderItem> orderItems = aOrderItemDao.getItemsByOrderNo(order.getOrderNo());
		setOrderItemProperty(orderItems,OrderVo);
		return OrderVo;
	}
	
	//封装订单项属性
	private void setOrderItemProperty(List<ActionorderItem> orderItems, ActionOrderVo orderVo) {
		// TODO Auto-generated method stub
		List<ActionorderItemVo> items =Lists.newArrayList();
		for(ActionorderItem orderItem:orderItems) {
			items.add(createOrderItemVo(orderItem));
		}
		orderVo.setOrderItems(items);
	}
	
	//封装订单项vo
	private ActionorderItemVo createOrderItemVo(ActionorderItem orderItem) {
		// TODO Auto-generated method stub
		ActionorderItemVo itemVo =new ActionorderItemVo();
		itemVo.setOrderNo(orderItem.getOrderNo());
		itemVo.setGoodsId(orderItem.getGoodsId());
		itemVo.setGoodsName(orderItem.getGoodsName());
		itemVo.setIconUrl(orderItem.getIconUrl());
		itemVo.setCurPrice(orderItem.getPrice());
		itemVo.setTotalPrice(orderItem.getTotalPrice());
		itemVo.setQuantity(orderItem.getQuantity());
		return itemVo;
	}

	//封装地址属性
	private void setAddressProperty(ActionOrder order, ActionOrderVo orderVo, boolean hasAdress) {
		// TODO Auto-generated method stub
		ActionAddress address= aaddressDao.findAddrsById(order.getAddrId());
		if (address!=null) {
			orderVo.setDeliverName(address.getName());
			if (hasAdress) {
				orderVo.setAddress(createAddressVo(address));
			}else {
				orderVo.setAddress(null);
			}
		}
		
	}
	
	//封装地址vo
	private ActionAddressVo createAddressVo(ActionAddress address) {
		// TODO Auto-generated method stub
		ActionAddressVo addressVo=new ActionAddressVo();
		addressVo.setName(address.getName());
		addressVo.setMobile(address.getMobile());
		addressVo.setPhone(address.getPhone());
		addressVo.setProvince(address.getProvince());
		addressVo.setCity(address.getCity());
		addressVo.setDistrict(address.getDistrict());
		addressVo.setAddr(address.getAddr());
		addressVo.setZip(address.getZip());

		
		return addressVo;
	}

	//封装订单的VO普通属性
	private void setNormalProperty(ActionOrder order, ActionOrderVo orderVo) {
		// TODO Auto-generated method stub
		orderVo.setOrderNo(order.getOrderNo());
		orderVo.setAmount(order.getAmount());
		orderVo.setType(order.getType());
		orderVo.setTypeDesc(ConstUtil.PaymentType.getTypeDesc(order.getType()));
		orderVo.setFreight(order.getFreight());
		orderVo.setStatus(order.getStatus());
		orderVo.setStatusDesc(ConstUtil.PaymentType.getTypeDesc(order.getStatus()));
		orderVo.setAddrId(order.getAddrId());
		//时间
		orderVo.setPaymentTime(DateUtils.date2Str(order.getPaymenTime()));
		orderVo.setDeliveryTime(DateUtils.date2Str(order.getDeliveryTime()));
		;
		orderVo.setFinishTime(DateUtils.date2Str(order.getFinishTime()));
		orderVo.setCloseTime(DateUtils.date2Str(order.getCloseTime()));
		orderVo.setCreated(DateUtils.date2Str(order.getCreateTime()));
		
	}

	
	
	

	//保存订单
	private ActionOrder saveOrder(Integer uid, Integer addrId, BigDecimal totalPrice) {
		// TODO Auto-generated method stub
		ActionOrder order=new ActionOrder();
		//生成订单号
		long currenTime=System.currentTimeMillis();
		Long orderNo=currenTime + new Random().nextInt(100);
		order.setOrderNo(orderNo);
		order.setStatus(ConstUtil.OrderStatus.ORDER_NO_PAY);
		order.setType(ConstUtil.PaymentType.PAY_ON_LINE);
		order.setFreight(0);
		order.setAmount(totalPrice);
		order.setAddrId(addrId);
		order.setUserId(uid);
		order.setUpdateTime(new Date());
		order.setCreateTime(new Date());
		//插入订单
		int rs=aOrderDao.insertOrder(order);
		if (rs>0) {
			return order;
		}
		return null;
	}

	//计算订单总价格
	private BigDecimal calcOrderTotalPrice(List<ActionorderItem> orderItems) {
		// TODO Auto-generated method stub
		BigDecimal totalPrice =new BigDecimal("0");
		for(ActionorderItem item:orderItems) {
			totalPrice=CalcUtil.add(totalPrice.doubleValue(), item.getTotalPrice().doubleValue());
		}
		return totalPrice;
	}

	//将购物车中商品封装为订单项
	private SverResponse cart2OrderItem(Integer uid, List<ActionCart> carts) {
		// TODO Auto-generated method stub
		List<ActionorderItem> items=Lists.newArrayList();
		//判断购物车是否为空
		if (CollectionUtils.isEmpty(carts)) {
			return SverResponse.createByErrorMessage("购物车为空，请选择要购买的商品");
		}
		for(ActionCart cart:carts) {
			//查看购物车的商品状态
			ActionProduct product =aProductDao.findProductById(cart.getProductId());
			if (ConstUtil.ProductStatus.STATUS_ON_SALE!=product.getStatus()) {
				return SverResponse.createByErrorMessage("商品"+product.getName()+"已经下架");
			}
			//查看库存
			if (cart.getQuantity()>product.getStock()) {
				return SverResponse.createByErrorMessage("商品"+product.getName()+"库存不足");
			}
			//封装订单项
			ActionorderItem orderItem =new ActionorderItem();
			orderItem.setUid(uid);
			orderItem.setGoodsName(product.getName());
			orderItem.setGoodsId(product.getId());
			orderItem.setIconUrl(product.getIconUrl());
			orderItem.setPrice(product.getPrice());
			orderItem.setQuantity(cart.getQuantity());
			orderItem.setTotalPrice(CalcUtil.mul(orderItem.getPrice().doubleValue(), orderItem.getQuantity().doubleValue()));
			orderItem.setCreated(new Date());
			orderItem.setUpdated(new Date());
			items.add(orderItem);
		}
		return SverResponse.createRespBySuccess(items);
	}
}
